﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Mani.Security;
using Mani.Common;

public partial class roles : BasePage
{
    public override string ActionName {
        get {
            return "vw_roles";
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            BindRolesToGridView();
    }

    private void BindRolesToGridView()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("RoleName");
        dt.Columns.Add("CountOfUsersInRole");
        string[] roles = Roles.GetAllRoles();

        foreach (string s in roles)
        {
            DataRow row = dt.NewRow();
            row[0] = s;
            row[1] = Roles.GetUsersInRole(s).Length;
            dt.Rows.Add(row);
        }

        gvRoles.DataSource = dt;
        gvRoles.DataBind();
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Roles.CreateRole(txtRoleName.Text);
        lblMessage.Text = "گروه با موفقیت ایجاد شد";
        txtRoleName.Text = "";
        BindRolesToGridView();
    }

    protected void gvRoles_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string rolename = gvRoles.DataKeys[e.RowIndex].Value.ToString();
        if (Roles.GetUsersInRole(rolename).Length > 0)
        {
            UIHelper.ClientAlert(this, "گروهی که دارای عضو است قابل حذف نیست");
            e.Cancel = true;
        }
        else
        {
            Roles.DeleteRole(rolename);
            BindRolesToGridView();
        }
    }

    protected void gvRoles_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType != DataControlRowType.DataRow)
            return;

        LinkButton lnkDelete = (LinkButton)e.Row.FindControl("DeleteRole");
        if (lnkDelete != null)
            lnkDelete.OnClientClick = @"return confirm('" + "آیا نسبت به حذف گروه " +
                            gvRoles.DataKeys[e.Row.RowIndex].Value.ToString() + " اطمینان دارید ؟" +
                            "');";
    }
}
